package com.shuyuntu.proposal.controller;

import com.shuyuntu.proposal.entity.Attachment;
import com.shuyuntu.proposal.service.AttachmentService;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * Created by limeng on 16-5-22.
 */
@Controller
@RequestMapping("/attachment")
public class AttachmentController {
    /**
     * 下载文件的控制器
     * TODO:未进行盗链、限速等操作
     * @param res 注入的响应对象实例
     * @param id 待下载文件的id
     * @throws IOException IO异常
     */
    @RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
    public void download(HttpServletResponse res, @PathVariable int id) throws IOException {
        OutputStream os = res.getOutputStream();
        Attachment attachment = attachmentService.getById(id);
        try {
            res.reset();
            res.setHeader("Content-Disposition", "attachment; filename=" + attachment.getFilename());
            res.setContentType("application/octet-stream; charset=utf-8");
            File baseDir = new File("");

            String filePath = null;

            if (attachment.getRealName() != null) {
                filePath = baseDir.getAbsolutePath() + "/" +
                                attachment.getPath() + "/" + attachment.getRealName();
            } else {
                filePath = baseDir.getAbsolutePath() + "/" +
                        attachment.getPath() + "/" + attachment.getFilename();
            }

            File file = new File(filePath);
            if (file.exists()) {
                os.write(FileUtils.readFileToByteArray(file));
                os.flush();
            } else {
                throw new IOException();
            }
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

    /**
     * 获取某个提案的附件列表
     * @param id 提案的id
     * @return list
     */
    @RequestMapping(value = "/proposalId/{id}", method = RequestMethod.GET)
    @ResponseBody
    List<Attachment> getListByProposalId(@PathVariable int id) {
        return attachmentService.getListByProposalId(id);
    }


    @Resource
    AttachmentService attachmentService;

    public AttachmentService getAttachmentService() {
        return attachmentService;
    }

    public void setAttachmentService(AttachmentService attachmentService) {
        this.attachmentService = attachmentService;
    }
}
